import React, { useState, useEffect } from 'react';
import { Input, Form } from '@alifd/next';
import { config, useRequest, useHistory } from 'ice';
import { getLogin} from '@/api/user';

import styles from './index.module.scss';

const { Item } = Form;

export interface IDataSource {
  email: string;
  password: string;
  imgCode: string;
}
const DEFAULT_DATA: IDataSource = {
  email: 'admin@shopshops.com',
  password: 'admin123456',
  imgCode: '',
};

interface LoginProps {
  dataSource?: IDataSource;
}


const LoginBlock: React.FunctionComponent<LoginProps> = (props = { dataSource: DEFAULT_DATA  }): JSX.Element => {
  const {
    dataSource = DEFAULT_DATA,
  } = props;

  const history = useHistory();
  const [postData, setValue] = useState(dataSource);
  const [codeImgUrl, setCodeImgUrl] = useState('');
  const [imgCodeKey, setCodeImgKey] = useState('');
  const {request } = useRequest(getLogin);


  const formChange = (values: IDataSource) => {
    setValue(values);
  };

    // 登录
  const loginClick = async (values: IDataSource, errors: []) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    const {code, result}: any = await request({
      ...values,
      imgCodeKey,
    });
    if (!code) {
      localStorage.setItem('token', result.token);
      history.push('/');
    }
  };

  // 获取验证码
  const getCodeImg = () => {
    const CodeKey = `${new Date().getTime()  }`;
    const url = `${config.baseURL}/admin/get-code-img?imgCodeKey=${CodeKey}`;
    setCodeImgUrl(url);
    setCodeImgKey(CodeKey);
  }
  useEffect(() => {
    getCodeImg();
  },[]);

  const accountForm = <>
    <Item required requiredMessage="请输入用户名">
      <Input
        name="email"
        maxLength={20}
        placeholder="用户名"
      />
    </Item>
    <Item required requiredMessage="请输入密码">
      <Input.Password
        name="password"
        htmlType="password"
        placeholder="密码"
      />
    </Item>
    <Item required requiredMessage="请输入验证码">
      <Input
        style={{ width: '60%' }}
        name="imgCode"
        placeholder="验证码"
      />
      <span className={styles.imgCode} onClick={getCodeImg}>
        <img  src={codeImgUrl} alt=""/>
      </span>
    </Item>
  </>;


  return (
      <div className={styles.LoginBlock}>
        <div className={styles.innerBlock}>
          <Form
            value={postData}
            onChange={formChange}
            size="large"
          >
            {accountForm}
            <Item style={{marginTop: 40}}>
              <Form.Submit
                type="primary"
                onClick={loginClick}
                className={styles.submitBtn}
                validate
              >
                Login
              </Form.Submit>
            </Item>
          </Form>
        </div>
      </div>
  );
}

export default LoginBlock;
